package com.ezgo.erc.utils;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ezgo.erc.dao.ISyslogDao;
import com.ezgo.erc.entity.Syslog;
import com.ezgo.erc.master.exception.DaoException;
import com.ezgo.erc.master.utils.SpringContext;
import com.ezgo.erc.master.utils.StringUtil;

/**
 * 
 * (工具)模块 TODO(日志记录工具)
 * 
 * @author devintam
 * @date 2015年7月20日 下午3:37:56
 *
 */
public class SysLogUtil {
	protected static Logger logger = LoggerFactory.getLogger(SysLogUtil.class);
	private static ISyslogDao logDao = SpringContext.getBean(ISyslogDao.class);

	/**
	 * 
	 * TODO(保存用户访问日志信息)
	 *
	 * @param request
	 * @param type
	 * @param msg
	 *            void
	 */
	public static void saveLog(HttpServletRequest request, String type, String msg) {
		StringBuilder params = new StringBuilder();
		int index = 0;

		for (Object param : request.getParameterMap().keySet()) {
			params.append((index++ == 0 ? "" : "&") + param + "=");
			params.append(StringUtil.abbr(StringUtil.endsWithIgnoreCase((String) param, "password") ? "" : request.getParameter((String) param), 100));
		}
		Syslog log = new Syslog();
		log.setType(type);
		log.setCreateBy(0L);
		log.setCreateDate(new Date());
		log.setRemoteAddr(StringUtil.getRemoteAddr(request));
		log.setUserAgent(request.getHeader("user-agent"));
		log.setRequestUrl(request.getRequestURI());
		log.setMethod(request.getMethod() == null ? "GET" : request.getMethod());
		log.setParams(params.toString());
		log.setExMsg(msg);
		try {
			logDao.insert(log);
		} catch (DaoException e) {
			e.printStackTrace();
		}
		logger.info(String.format("save log {type: {}, loginName: {}, uri: {}}, ", log.getType(), "", log.getRequestUrl()));
	}

	/**
	 * 
	 * TODO(保存用户访问日志信息)
	 *
	 * @param request
	 * @param type
	 * @param msg
	 *            void
	 */
	public static void saveLog(Syslog log) {
		try {
			logDao.insert(log);
		} catch (DaoException e) {
			e.printStackTrace();
		}
		logger.info(String.format("save log {type: {}, loginName: {}, uri: {}}, ", log.getType(), "", log.getRequestUrl()));
	}
}
